<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-03-18 22:48:30
 */

namespace app\admin\logic;
use app\common\logic\Base as BaseLogic;

class AdminUser extends BaseLogic {
	// 设置数据表（不含前缀）
	protected $name = 'admin_user';

	function initialize() {
		parent::initialize();
		$this->adminUserDao = model('admin/AdminUser');
	}
	
	public function login($username, $password, $rememberme = false) {
		if (config('app.admin_is_uc')) {
			return $this->ucLogin($username, $password, $rememberme);
		} else {
			return $this->dbLogin($username, $password, $rememberme);
		}
	}
	
	public function dbLogin($username, $password, $rememberme = false) {
		$md5Password = sp_password($password);
		
		//获取用户信息
		$userInfo = $this->adminUserDao->getInfoByUsername($username);
		//print_r($userInfo);exit;

		if (!empty($userInfo)) {
			/* 验证用户密码 */
			if ($md5Password === $userInfo['password']) {
				//echo 'md5Password:'.$md5Password;echo 'password:'.$user['password'];print_r($user);
				if (!$userInfo['state']) {
					return ['code'=>500,'msg'=>'您的账号禁止登陆'];
				}
				//if (!$user['allow_admin']) {
					//return ['code'=>500,'msg'=>'您的账号不允许登录后台'];
				//}

				//获取组别信息
				$authGroupDao = model('admin/AuthGroup');
				$groupInfo = $authGroupDao->getInfo($userInfo['groupid']);
				if (!$groupInfo['allow_admin']) {
					return ['code'=>500,'msg'=>'您的组别不允许登录后台'];
				}

				self::autoLogin($userInfo, $rememberme); //更新用户登录信息
				return ['code'=>200,'msg'=>'登录成功','data'=>['id'=>$user['id']]];
			} else {
				return ['code'=>500,'msg'=>'用户名或密码错误'];
			}
		} else {
			return ['code'=>500,'msg'=>'用户不存在或被禁用'];
		}
	}

	public function ucLogin($username, $password, $rememberme = false) {
		//db('Aaaa')->insert(['space'=>'admin', 'module'=>'login', 'flag'=>'ucLogin', 'content'=>'000']);
		$md5Password = sp_password($password);

		include UC_CLIENT_ROOT."client.php";
		list($uid, $username, $md5Password, $email, $mobile, $groupid) = uc_user_login($username, $md5Password);
		if ($uid == -1) {
			return ['code'=>500,'msg'=>'用户名或密码错误'];
		}
		if ($uid == -2) {
			return ['code'=>500,'msg'=>'密码错误'];
		}
		if (!$groupid || !$mobile || !$avatar) {
			db('Aaaa')->insert(['space'=>'admin', 'module'=>'login', 'flag'=>'ucLogin', 'content'=>'3']);
			$membersDao = model('Common/Members');
			//echo $uid;exit;
			$memberInfo = $membersDao->getInfo($uid);
			//print_r($memberInfo);exit;
			$mobile = $memberInfo['authmobile'];
			$groupid = $memberInfo['groupid'];
			$avatar = getAvatarByIcon($memberInfo['icon']);
		} else {
			//$avatar = self::getAvatarByIcon($avatar);
		}
		//db('Aaaa')->insert(['space'=>'admin', 'module'=>'login', 'flag'=>'ucLogin', 'content'=>'4']);

		$user = [
			'id' => $uid,
			'username' => $username,
			'password' => $md5Password,
			'mobile' => $mobile,
			'groupid' => 0,
			'email' => $email,
			'avatar' => $avatar,
		];

		if ($uid) {
			/* 验证用户密码 */
			// if(encrypt($password) === $user['password']){
			// 	self::autoLogin($user, $rememberme); //更新用户登录信息
			// 	return ['code'=>200,'msg'=>'登录成功','data'=>['uid'=>$user['uid']]];
			// } else {
			// 	return ['code'=>500,'msg'=>'密码错误！'];
			// }
			$localUser = $this->adminUserDao->getInfo($user['id']);
			if (empty($localUser)) {
				$user['create_time'] = time();
				$this->adminUserDao->baseAddData($user);
			} else {
				//更新用户表密码字段
				$data = [
					'password' => $md5Password,
				];
				$this->adminUserDao->baseUpdateData($user['id'], $data);
			}
			//if ($localUser['state'] == 0) {
				//return ['code'=>500,'msg'=>'您的账号禁止登陆'];
			//}
			self::autoLogin($user, $rememberme); //更新用户登录信息

			$syn = '';
			//不开启同步登陆
			if (config('app.UCENTER_LOGIN')) {
				$syn = uc_user_synlogin($user['id']);
			}
			return ['code'=>200,'msg'=>'登录成功','data'=>['uid'=>$user['id']]];
		} else {
			return ['code'=>500,'msg'=>'用户不存在或被禁用！'];
		}

		return false;
	}
	
	/**
	 * 自动登录
	 * @param  [type]  $user	   用户对象
	 * @param  boolean $rememberme 是否记住登录，默认7天
	 * @return [type]			   [description]
	 */
	public function autoLogin($user, $rememberme = true, $rememberTime = 600){
		if (empty($user)) return false;
		//echo 'user:';print_r($user);exit;

		$request = request();
		$ipaddr = $request->ip();
		
		//更新管理员信息
		$data = [
			'last_login_ip'		=> $ipaddr,
			'last_login_time' 	=> time(),
		];
		$this->adminUserDao->baseUpdateData($user['id'], $data);

		// 记录登录SESSION和COOKIES
		// $result = self::setUserAuthSession($user);
		// $auth_login = $result['auth_login'];
		// $auth_login_sign = $result['auth_login_sign'];
		// // 更新登录信息
		// $data = [
		// 	'last_login_ip'		   => request()->ip(),
		// 	'last_login_time'	   => $auth_login['last_login_time'],
		// 	'activation_auth_sign' => $auth_login_sign,
		// ];
		//
		// self::where(['uid' => $auth_login['uid']])->update($data);

		// 记住登录
		if ($rememberme) {
			cookie('admin_login_auth', _authcode($user['id']."\t".$user['password'], 'ENCODE'), 24 * 3600 * 30);
			//todo
			//$list = explode("\t", addslashes(_authcode(cookie('admin_login_auth'))));
			//print_r($list);exit;
		} else {
			cookie('admin_login_auth', _authcode($user['id']."\t".$user['password'], 'ENCODE'), $rememberTime); //, config('COOKIE_EXPIRE')
		}
	}

	/**
	 * 判断是否登录
	 * @return int 0或用户id
	 */
	public static function isLogin() {
		$list = explode("\t", addslashes(_authcode(cookie('admin_login_auth'))));
		//echo 'list:';print_r($list);exit;
		if (count($list) > 1) {
			list($winduid, $windpwd) = $list;
		}
		if ($winduid) {
			return array($winduid, $windpwd);
		} else {
			return array(0);
		}
	}

	public function logout() {
		cookie('admin_login_auth', null);
	}

}